package com.dq.service.config.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dq.exception.customException.AdminException;
import com.dq.vo.Vo;
import com.dq.domain.evaluation.EvaluationTemplate;
import com.dq.domain.evaluation.EvaluationTemplateChild;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.config.EvaluationTemplateChildService;
import com.dq.service.config.EvaluationTemplateService;
import com.dq.service.sys.user.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cf
 * <p>
 */
@Service
public class EvaluationTemplateServiceImpl extends BaseRepositories implements EvaluationTemplateService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    protected EvaluationTemplateChildService evaluationTemplateChildService;

    /**
     * 获取模板（评分。。。）
     */
    @Override
    public Vo getInfo(EvaluationTemplate template) throws AdminException {
        if(template == null) {
            throw new AdminException("未找到对应模板");
        }
        JSONObject mainJaon = new JSONObject();
        mainJaon.put("id", template.getId());
        mainJaon.put("name", template.getName());
        mainJaon.put("sort", template.getSort());

        Map<String, Object> queryMajor = new HashMap<>(16);
        queryMajor.put("parent", template);
        queryMajor.put("sidx", "sort");
        queryMajor.put("order", "asc");
        List<EvaluationTemplate> majorList = dao.find(dao.query2Hql(EvaluationTemplate.class, queryMajor), queryMajor);
        JSONArray majorArray = new JSONArray();
        for (EvaluationTemplate major : majorList) {
            JSONObject majorJson = new JSONObject();
            majorJson.put("id", major.getId());
            majorJson.put("name", major.getName());
            majorJson.put("sort", major.getSort());

            Map<String, Object> queryMinor = new HashMap<>(16);
            queryMinor.put("evaluationTemplate", major);
            queryMinor.put("sidx", "sort");
            queryMinor.put("order", "asc");
            List<EvaluationTemplateChild> minorList = dao.find(dao.query2Hql(EvaluationTemplateChild.class, queryMinor), queryMinor);
            JSONArray minorArray = new JSONArray();
            for (EvaluationTemplateChild child : minorList) {
                JSONObject minorJson = new JSONObject();
                minorJson.put("id", child.getId());
                minorJson.put("name", child.getTitle());
                minorJson.put("sort", child.getSort());
                minorJson.put("score", child.getScore());
                minorArray.add(minorJson);
            }
            majorJson.put("minorArray", minorArray);

            majorArray.add(majorJson);
        }
        mainJaon.put("majorArray", majorArray);

        return new Vo(mainJaon);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Vo saveUpdate(JSONObject jsonObject, EvaluationTemplate paren) throws AdminException {
        // 模板主项信息
        String majorString = "majorArray";
        // 模板主项下级信息
        String minorString = "minorArray";
        // 名称
        String nameString = "name";
        // 名称
        String sortString = "sort";
        // 子项目, 代表多少评分
        String scoreString = "score";
        String idString = "id";
        try {
            /// 删除模板子项/子项
            List<EvaluationTemplate> evaluationTemplateList = evaluationTemplateRepository.findByDeletedFalseAndParentOrderBySortAsc(paren);
            if(evaluationTemplateList != null && evaluationTemplateList.size() > 0) {
                List<EvaluationTemplateChild> childAllList = new ArrayList<>();
                for (EvaluationTemplate evaluationTemplate : evaluationTemplateList) {
                    List<EvaluationTemplateChild> childList = evaluationTemplateChildRepository.findByEvaluationTemplateAndDeletedFalseOrderBySortAsc(evaluationTemplate);
                    if(childList != null && childList.size() > 0) {
                        childAllList.addAll(childList);
                    }
                }
                evaluationTemplateChildRepository.deleteAll(childAllList);
                evaluationTemplateRepository.deleteAll(evaluationTemplateList);
            }

            JSONArray majorArray = jsonObject.getJSONArray(majorString);
            List<EvaluationTemplate> listSave = new ArrayList<>();
            List<EvaluationTemplateChild> listChildSave = new ArrayList<>();
            for (Object major : majorArray) {
                JSONObject majorJson = JSONObject.parseObject(major.toString());
                if(majorJson.get(nameString) == null || majorJson.get(sortString) == null
                        || StringUtils.isBlank(majorJson.get(nameString).toString()) || StringUtils.isBlank(majorJson.get(sortString).toString())) {
                    throw new AdminException("模板主项参数异常");
                }
                String majorName = majorJson.get(nameString).toString();
                String majorSort = majorJson.get(sortString).toString();

                EvaluationTemplate template = new EvaluationTemplate(majorName, Long.parseLong(majorSort), paren);
                if (majorJson.get(idString) != null && StringUtils.isNotBlank(majorJson.get(idString).toString())) {
//                    EvaluationTemplate getEvaluationTemplate = dao.get(EvaluationTemplate.class, Long.parseLong(majorJson.get(idString).toString()));
//                    if(getEvaluationTemplate == null) {
//                        throw new AdminException("模板主项不存在");
//                    }
//                    BeanUtils.copyProperties(template, getEvaluationTemplate, BeanNullUtil.getNullPropertyNames(template));
//                    template = getEvaluationTemplate;
                }
                saveUpdate(template);
//                listSave.add(template);

                JSONArray minorArray = majorJson.getJSONArray(minorString);
                for (Object minor : minorArray) {
                    JSONObject minorJson = JSONObject.parseObject(minor.toString());
                    if(minorJson.get(nameString) == null || minorJson.get(scoreString) == null || minorJson.get(sortString) == null
                            || StringUtils.isBlank(minorJson.get(nameString).toString()) || StringUtils.isBlank(minorJson.get(scoreString).toString()) || StringUtils.isBlank(minorJson.get(sortString).toString())) {
                        throw new AdminException("模板子项参数异常");
                    }
                    String minorName = minorJson.get(nameString).toString();
                    String minorScore = minorJson.get(scoreString).toString();
                    String minorSort = minorJson.get(sortString).toString();
                    EvaluationTemplateChild evaluationTemplateChild = new EvaluationTemplateChild(minorName, Long.parseLong(minorScore), Long.parseLong(minorSort), template);
                    if (minorJson.get(idString) != null && StringUtils.isNotBlank(minorJson.get(idString).toString())) {
//                        EvaluationTemplateChild getEvaluationTemplateChild = dao.get(EvaluationTemplateChild.class, Long.parseLong(minorJson.get(idString).toString()));
//                        if(getEvaluationTemplateChild == null) {
//                            throw new AdminException("模板子项不存在");
//                        }
//                        BeanUtils.copyProperties(evaluationTemplateChild, getEvaluationTemplateChild, BeanNullUtil.getNullPropertyNames(evaluationTemplateChild));
//                        evaluationTemplateChild = getEvaluationTemplateChild;
                    }
                    evaluationTemplateChildService.saveUpdate(evaluationTemplateChild);
//                    listChildSave.add(evaluationTemplateChild);
                }
            }

//            saveUpdateList(listSave);
//            evaluationTemplateChildService.saveUpdateList(listChildSave);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存数据异常, " + e.getMessage());
        }
        return new Vo(HttpStatus.OK);
    }

    /**
     * 添加/修改, 批量
     */
    @Override
    public List<EvaluationTemplate> saveUpdateList(List<EvaluationTemplate> list) throws AdminException {
        if (list == null || list.size() <= 0) {
            throw new AdminException("集合为空");
        }
        List<EvaluationTemplate> listSave = new ArrayList<>();
        for (EvaluationTemplate evaluationTemplate : list) {
            if (evaluationTemplate == null) {
                throw new AdminException("保存对象为空");
            }
            if (evaluationTemplate.getId() != null) {
                evaluationTemplate = objectUpdateBase(evaluationTemplate);
            } else {
                evaluationTemplate = objectSaveBase(evaluationTemplate);
            }

            listSave.add(evaluationTemplate);
        }

        dao.saveOrModifyList(listSave);
        return listSave;
    }

    /**
     * 添加/修改
     */
    @Override
    public EvaluationTemplate saveUpdate(@Valid EvaluationTemplate evaluationTemplate) throws AdminException {
        if (evaluationTemplate == null) {
            throw new AdminException("保存对象为空");
        }
        if (evaluationTemplate.getId() != null) {
            evaluationTemplate = objectUpdateBase(evaluationTemplate);
        } else {
            evaluationTemplate = objectSaveBase(evaluationTemplate);
        }

        return evaluationTemplateRepository.save(evaluationTemplate);
    }

    /**
     * 添加对象基本属性配置
     */
    @Override
    public EvaluationTemplate objectSaveBase(EvaluationTemplate evaluationTemplate) throws AdminException {
        SysUser user = sysUserService.getUser();
        evaluationTemplate.setCreateUser(user);
        evaluationTemplate.setUpdateUser(user);

        return evaluationTemplate;
    }

    /**
     * 修改对象基本属性配置
     */
    @Override
    public EvaluationTemplate objectUpdateBase(EvaluationTemplate evaluationTemplate) throws AdminException {
        SysUser user = sysUserService.getUser();
        if (user != null) {
            evaluationTemplate.setUpdateUser(user);
        }

        return evaluationTemplate;
    }

}

